package spring.framework.beans.factory.xml;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import spring.framework.beans.BeansException;
import spring.framework.beans.PropertyValue;
import spring.framework.beans.factory.config.BeanDefinition;
import spring.framework.beans.factory.config.BeanReference;
import spring.framework.beans.factory.support.AbstractBeanDefinitionReader;
import spring.framework.beans.factory.support.BeanDefinitionRegistry;
import spring.framework.core.io.Resource;
import spring.framework.core.io.ResourceLoader;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author fun.pengzh
 * @class spring.framework.beans.factory.xml.XmlBeanDefinitionReader
 * @desc 读取xml形式Bean
 * @since 2021-10-10
 */
public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {

    public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
        super(registry);
    }

    public XmlBeanDefinitionReader(BeanDefinitionRegistry registry, ResourceLoader resourceLoader) {
        super(registry, resourceLoader);
    }

    @Override
    public void loadBeanDefinitions(Resource resource) throws BeansException {
        try (InputStream inputStream = resource.getInputStream()) {
            doloadBeanDefinitions(inputStream);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void loadBeanDefinitions(Resource... resources) throws BeansException {
        for (Resource resource : resources) {
            loadBeanDefinitions(resource);
        }
    }

    @Override
    public void loadBeanDefinitions(String location) throws BeansException {
        ResourceLoader resourceLoader = getResourceLoader();
        Resource resource = resourceLoader.getResource(location);
        loadBeanDefinitions(resource);
    }

    @Override
    public void loadBeanDefinitions(String... locations) throws BeansException {
        for (String location : locations) {
            loadBeanDefinitions(location);
        }
    }

    protected void doloadBeanDefinitions(InputStream inputStream) throws ClassNotFoundException {
        Document doc = XmlUtil.readXML(inputStream);
        Element root = doc.getDocumentElement();
        NodeList childNodes = root.getChildNodes();

        for (int i = 0; i < childNodes.getLength(); i++) {
            Node childNode = childNodes.item(i);

            if (!(childNode instanceof Element)) continue;
            if (!"bean".equals(childNode.getNodeName())) continue;

            //解析标签
            Element bean = (Element) childNode;
            String id = bean.getAttribute("id");
            String name = bean.getAttribute("name");
            String className = bean.getAttribute("class");
            String initMethodName = bean.getAttribute("init-method");
            String destroyMethodName = bean.getAttribute("destroy-method");

            Class<?> clazz = Class.forName(className);
            String beanName = StrUtil.isNotBlank(id) ? id : name;
            beanName = StrUtil.isNotBlank(beanName) ? beanName : StrUtil.lowerFirst(clazz.getSimpleName());

            //定义bean
            BeanDefinition beanDefinition = new BeanDefinition(clazz);
            beanDefinition.setInitMethoName(initMethodName);
            beanDefinition.setDestroyMethodName(destroyMethodName);

            //读取属性并填充
            NodeList grandSonNodes = bean.getChildNodes();
            for (int j = 0; j < grandSonNodes.getLength(); j++) {
                Node grandSonNode = grandSonNodes.item(j);
                if (!(grandSonNodes.item(j) instanceof Element)) continue;
                ;
                if (!"property".equals(grandSonNode.getNodeName())) continue;

                Element property = (Element) grandSonNode;
                String attrName = property.getAttribute("name");
                String attrValue = property.getAttribute("value");
                String attrRef = property.getAttribute("ref");
                Object value = StrUtil.isNotBlank(attrRef) ? new BeanReference(attrRef) : attrValue;

                PropertyValue propertyValue = new PropertyValue(attrName, value);
                beanDefinition.getPropertyValues().addPropertyValue(propertyValue);
            }
            if (getRegistry().containsBeanDefinition(beanName)) {
                throw new BeansException("Duplicate beanName[" + beanName + "] is not allowed");
            }
            getRegistry().registerBeanDefinition(beanName, beanDefinition);
        }
    }
}
